import logging

from aiogram import Bot
from fluentogram import TranslatorRunner

from src.application.order.enums import OrderType
from src.application.order.service import OrderService
from src.application.user.service import UserService
from src.infrastructure.date_helpers import format_datetime, get_date_time
from src.presentation.tg_bot.services.locale import Localizator
from src.presentation.tg_bot.services.tg_helpers import send_tg_message
from src.presentation.tg_bot.worker.exception_handler import exception_handler

logger = logging.getLogger(__name__)


@exception_handler
async def notify_expiring_orders(ctx) -> None:
    bot: Bot = ctx["bot"]
    # session: AsyncSession = ctx["session"]
    order_service: OrderService = ctx["order_service"]
    user_service: UserService = ctx["user_service"]
    bot_settings_service: BotSettingsService
    fluent: Localizator = ctx["fluent"]

    bot_settings = await get_bot_settings(session)
    if bot_settings and bot_settings.order_notify_status:
        orders = await order_service.get_expiring_orders()
        for order in orders:
            cur_date = get_date_time()
            user = await user_service.get_user_by_id(order.buyer_id)
            locale: TranslatorRunner = fluent.get_by_locale(user.lang_code)
            expiring_on = format_datetime(order.expiring_on)
            if order.order_type == OrderType.subscription:
                extend_msg = locale.get(
                    "subscription-expiring",
                    expiring_on=expiring_on,
                )
            elif order.order_type == OrderType.vpn:
                extend_msg = locale.get(
                    "vpn-expiring",
                    expiring_on=expiring_on,
                )
            else:
                extend_msg = locale.get(
                    "order-expiring",
                    order_id=str(order.id),
                    order_summ=order.summ,
                    expiring_on=expiring_on,
                )

            await send_tg_message(bot, user.tg_id, extend_msg)
            order.last_notified = cur_date

            logger.info(f"Отправил напоминание о продлении заказа/подписки №{order.id}")
